package com.addzero.web.ui.components.drawer

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.outlined.CloudUpload
import androidx.compose.material.icons.outlined.ContentPaste
import androidx.compose.material.icons.outlined.Description
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.awt.ComposePanel
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.addzero.web.ui.components.drawer.DrawerDirection.*
import com.addzero.web.ui.hooks.UseHook
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.awt.FileDialog
import java.awt.Frame
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor
import java.awt.dnd.DnDConstants
import java.awt.dnd.DropTarget
import java.awt.dnd.DropTargetAdapter
import java.awt.dnd.DropTargetDropEvent
import java.io.File
import javax.swing.JPanel
import javax.swing.SwingUtilities
import kotlin.math.roundToInt


/**
 * 上传文件数据类
 */
data class UploadFile( val name: String, val content: ByteArray )
/**
 * 多文件上传结果
 */
data class UploadResult(
    val files: List<UploadFile> = emptyList()
)

/**
 * 上传抽屉 UseHook
 */
class UseUploadDrawer(
    // 抽屉方向，默认从顶部展开
    val direction: DrawerDirection = DrawerDirection.TOP
) : UseHook<UseUploadDrawer> {
    // 抽屉展开状态
    var isExpanded by mutableStateOf(false)
    // 已选择的多个文件
    var selectedFiles by mutableStateOf<List<File>>(emptyList())
    // 上传后的文件内容和名称
    var uploadResult by mutableStateOf<UploadResult?>(null)

    // 是否处于拖拽状态
    var isDragging by mutableStateOf(false)
    // 抽屉位置偏移量
    var offset by mutableStateOf(0f)

    // 协程作用域
    private val coroutineScope = CoroutineScope(Dispatchers.Default)

    // 处理文件上传逻辑
    fun upload() {
        if (selectedFiles.isNotEmpty()) {
            val fileData = selectedFiles.map { file ->
                UploadFile(file.name, file.readBytes())
            }
            uploadResult = UploadResult(fileData)

            // 成功上传后关闭抽屉
            toggleDrawer()
        }
    }

    // 打开文件选择器
    fun openFileSelector() {
        coroutineScope.launch {
            selectMultipleFiles()?.let { files ->
                selectedFiles = files
            }
        }
    }

    // 处理拖拽开始
    fun onDragEnter() {
        isDragging = true
    }

    // 处理拖拽结束
    fun onDragExit() {
        isDragging = false
    }

    // 处理文件拖放
    fun onFileDrop(files: List<File>) {
        selectedFiles = files
        isDragging = false
    }

    // 切换抽屉状态
    fun toggleDrawer() {
        isExpanded = !isExpanded
        // 重置偏移量
        offset = 0f
    }

    // 从剪贴板粘贴文件
    fun pasteFromClipboard() {
        try {
            val clipboard = Toolkit.getDefaultToolkit().systemClipboard
            if (clipboard.isDataFlavorAvailable(DataFlavor.javaFileListFlavor)) {
                // 修复unchecked cast警告
                val transferData = clipboard.getData(DataFlavor.javaFileListFlavor)
                if (transferData is List<*>) {
                    val files = transferData.filterIsInstance<File>()
                    if (files.isNotEmpty()) {
                        selectedFiles = files
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 清除选择的文件
    fun clearSelection() {
        selectedFiles = emptyList()
        uploadResult = null
    }

    // 移除指定文件
    fun removeFile(file: File) {
        selectedFiles = selectedFiles.filter { it != file }
    }

    @OptIn(ExperimentalComposeUiApi::class)
    override val render: @Composable () -> Unit = {
        // 创建一个面板来处理拖拽
        val dragTargetPanel = remember { JPanel().apply { layout = null } }

        // 设置拖放目标
        DisposableEffect(Unit) {
            val dropTargetListener = object : DropTargetAdapter() {
                override fun drop(event: DropTargetDropEvent) {
                    try {
                        event.acceptDrop(DnDConstants.ACTION_COPY)
                        val transferable = event.transferable

                        if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                            // 修复unchecked cast警告
                            val transferData = transferable.getTransferData(DataFlavor.javaFileListFlavor)
                            if (transferData is List<*>) {
                                val files = transferData.filterIsInstance<File>()
                                if (files.isNotEmpty()) {
                                    onFileDrop(files)
                                }
                            }
                        }
                        event.dropComplete(true)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        event.dropComplete(false)
                    } finally {
                        onDragExit()
                    }
                }

                override fun dragEnter(event: java.awt.dnd.DropTargetDragEvent) {
                    if (event.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                        onDragEnter()
                        event.acceptDrag(DnDConstants.ACTION_COPY)
                    } else {
                        event.rejectDrag()
                    }
                }

                override fun dragExit(event: java.awt.dnd.DropTargetEvent) {
                    onDragExit()
                }
            }

            val dropTarget = DropTarget(dragTargetPanel, dropTargetListener)

            onDispose {
                dropTarget.removeDropTargetListener(dropTargetListener)
            }
        }

        // 创建一个ComposePanel来集成Swing和Compose
        LaunchedEffect(Unit) {
            val composePanel = ComposePanel()
            composePanel.setContent {
                Box(modifier = Modifier.fillMaxSize())
            }

            dragTargetPanel.add(composePanel)
            composePanel.setBounds(0, 0, 1, 1)
        }

        // 根据方向确定拖拽方向
        val dragOrientation = when (direction) {
            TOP, BOTTOM -> Orientation.Vertical
            LEFT, RIGHT -> Orientation.Horizontal
            FULLSCREEN -> Orientation.Vertical // 全屏模式使用垂直方向拖拽
        }

        // 辅助函数：处理拖拽逻辑，根据方向和状态更新偏移量
        fun handleDragOffset(newOffset: Float, threshold: Float, isPositiveDirection: Boolean): Float {
            return when {
                // 已展开状态下，限制向内拖拽
                isExpanded && (if (isPositiveDirection) newOffset > 0 else newOffset < 0) -> 0f
                // 已展开状态下，向外拖拽超过阈值，收起抽屉
                isExpanded && (if (isPositiveDirection) newOffset < -threshold else newOffset > threshold) -> {
                    isExpanded = false
                    0f
                }
                // 未展开状态下，向内拖拽超过阈值，展开抽屉
                !isExpanded && (if (isPositiveDirection) newOffset > threshold else newOffset < -threshold) -> {
                    isExpanded = true
                    0f
                }
                // 其他情况，正常更新偏移量
                else -> newOffset
            }
        }
        
        // 拖拽状态
        val draggableState = rememberDraggableState { delta ->
            // 更新拖拽偏移量
            val newOffset = offset + delta
            val threshold = 300f

            // 根据方向限制拖拽范围
            offset = when (direction) {
                // 顶部抽屉：向下为正方向
                TOP -> handleDragOffset(newOffset, threshold, false)
                // 底部抽屉：向上为正方向
                BOTTOM -> handleDragOffset(newOffset, threshold, true)
                // 左侧抽屉：向右为正方向
                LEFT -> handleDragOffset(newOffset, threshold, false)
                // 右侧抽屉：向左为正方向
                RIGHT -> handleDragOffset(newOffset, threshold, true)
                // 全屏模式：使用与顶部抽屉相同的逻辑
                FULLSCREEN -> handleDragOffset(newOffset, threshold, false)
            }
        }

        // 计算抽屉尺寸
        val drawerWidth = 400.dp
        val drawerHeight = 400.dp

        val drawerWidthPx = with(LocalDensity.current) { drawerWidth.toPx() }
        val drawerHeightPx = with(LocalDensity.current) { drawerHeight.toPx() }

        // 计算实际偏移量
        val actualOffset = when (direction) {
            TOP -> {
                if (isExpanded) {
                    IntOffset(0, offset.roundToInt())
                } else {
                    IntOffset(0, (-drawerHeightPx + 40f).roundToInt() + offset.roundToInt())
                }
            }
            BOTTOM -> {
                if (isExpanded) {
                    IntOffset(0, offset.roundToInt())
                } else {
                    IntOffset(0, (drawerHeightPx - 40f).roundToInt() + offset.roundToInt())
                }
            }
            LEFT -> {
                if (isExpanded) {
                    IntOffset(offset.roundToInt(), 0)
                } else {
                    IntOffset((-drawerWidthPx + 40f).roundToInt() + offset.roundToInt(), 0)
                }
            }
            RIGHT -> {
                if (isExpanded) {
                    IntOffset(offset.roundToInt(), 0)
                } else {
                    IntOffset((drawerWidthPx - 40f).roundToInt() + offset.roundToInt(), 0)
                }
            }
            FULLSCREEN -> {
                if (isExpanded) {
                    IntOffset(0, offset.roundToInt())
                } else {
                    IntOffset(0, (-drawerHeightPx + 40f).roundToInt() + offset.roundToInt())
                }
            }
        }

        // 抽屉形状
        val shape = when (direction) {
            TOP -> RoundedCornerShape(bottomStart = 16.dp, bottomEnd = 16.dp)
            BOTTOM -> RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)
            LEFT -> RoundedCornerShape(topEnd = 16.dp, bottomEnd = 16.dp)
            RIGHT -> RoundedCornerShape(topStart = 16.dp, bottomStart = 16.dp)
            FULLSCREEN -> RoundedCornerShape(0.dp) // 全屏模式无圆角
        }

        // 获取抽屉方向指示图标 - 箭头始终指向屏幕中央
        // 使用AutoMirrored版本替换已弃用图标
        val directionIcon = when (direction) {
            TOP -> if (isExpanded) Icons.Filled.KeyboardArrowDown else Icons.Filled.KeyboardArrowUp
            BOTTOM -> if (isExpanded) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown
            LEFT -> if (isExpanded) Icons.AutoMirrored.Filled.KeyboardArrowRight else Icons.AutoMirrored.Filled.KeyboardArrowLeft
            RIGHT -> if (isExpanded) Icons.AutoMirrored.Filled.KeyboardArrowLeft else Icons.AutoMirrored.Filled.KeyboardArrowRight
            FULLSCREEN -> if (isExpanded) Icons.Filled.KeyboardArrowDown else Icons.Filled.KeyboardArrowUp // 全屏模式使用顶部样式的图标
        }

        // 抽屉位置
        val drawerAlignment = when (direction) {
            TOP -> Alignment.TopCenter
            BOTTOM -> Alignment.BottomCenter
            LEFT -> Alignment.CenterStart
            RIGHT -> Alignment.CenterEnd
            FULLSCREEN -> Alignment.Center // 全屏模式居中显示
        }

        // 抽屉文字方向
        val isVertical = direction == DrawerDirection.LEFT || direction == DrawerDirection.RIGHT

        // 上传抽屉
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = drawerAlignment
        ) {
            // 抽屉内容
            Box(
                modifier = Modifier
                    .offset { actualOffset }
                    .let {
                        when (direction) {
                            TOP, BOTTOM ->
                                it.fillMaxWidth().height(drawerHeight)
                            LEFT, RIGHT ->
                                it.fillMaxHeight().width(drawerWidth)

                            FULLSCREEN ->
                                it.fillMaxSize().padding(16.dp) // 全屏模式填满并添加内边距
                        }
                    }
                    .clip(shape)
                    .background(MaterialTheme.colorScheme.surface)
                    .draggable(
                        state = draggableState,
                        orientation = dragOrientation
                    )
            ) {
                // 抽屉内容
                if (isVertical) {
                    // 水平抽屉（左/右）
                    Row(
                        modifier = Modifier.fillMaxSize()
                    ) {
                        // 拖拽手柄
                        Box(
                            modifier = Modifier
                                .fillMaxHeight()
                                .width(40.dp)
                                .clickable { toggleDrawer() },
                            contentAlignment = Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally,
                                verticalArrangement = Arrangement.Center
                            ) {
                                Icon(
                                    imageVector = directionIcon,
                                    contentDescription = if (isExpanded) "收起" else "展开",
                                    tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Text(
                                    text = if (isExpanded) "上传文件" else "上传",
                                    style = MaterialTheme.typography.titleMedium,
                                    color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f),
                                    modifier = Modifier.wrapContentWidth()
                                )
                            }
                        }

                        // 分隔线
                        Box(
                            modifier = Modifier
                                .width(1.dp)
                                .fillMaxHeight()
                                .background(MaterialTheme.colorScheme.outlineVariant)
                        )

                        // 抽屉内容区域
                        if (isExpanded) {
                            Box(
                                modifier = Modifier
                                    .weight(1f)
                                    .fillMaxHeight()
                            ) {
                                // 将Swing面板添加到Compose中用于处理拖放
                                SwingUtilities.invokeLater {
                                    dragTargetPanel.setSize(500, 300)
                                }

                                // 文件上传内容
                                UploadContent(
                                    selectedFiles = selectedFiles,
                                    isDragging = isDragging,
                                    onOpenFileSelector = { openFileSelector() },
                                    onRemoveFile = { removeFile(it) },
                                    onPasteFromClipboard = { pasteFromClipboard() },
                                    onUpload = { upload() }
                                )
                            }
                        }
                    }
                } else {
                    // 垂直抽屉（上/下）
                    Column(
                        modifier = Modifier.fillMaxSize()
                    ) {
                        // 拖拽手柄
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(40.dp)
                                .clickable { toggleDrawer() },
                            contentAlignment = Alignment.Center
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Center
                            ) {
                                Icon(
                                    imageVector = directionIcon,
                                    contentDescription = if (isExpanded) "收起" else "展开",
                                    tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Text(
                                    text = if (isExpanded) "上传文件" else "上传",
                                    style = MaterialTheme.typography.titleMedium,
                                    color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f)
                                )
                            }
                        }

                        // 分隔线 - 用HorizontalDivider替换已弃用的Divider
                        HorizontalDivider()

                        // 抽屉内容区域
                        if (isExpanded) {
                            Box(
                                modifier = Modifier
                                    .weight(1f)
                                    .fillMaxWidth()
                            ) {
                                // 将Swing面板添加到Compose中用于处理拖放
                                SwingUtilities.invokeLater {
                                    dragTargetPanel.setSize(500, 300)
                                }

                                // 文件上传内容
                                UploadContent(
                                    selectedFiles = selectedFiles,
                                    isDragging = isDragging,
                                    onOpenFileSelector = { openFileSelector() },
                                    onRemoveFile = { removeFile(it) },
                                    onPasteFromClipboard = { pasteFromClipboard() },
                                    onUpload = { upload() }
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

/**
 * 上传内容组件 - 提取共享的上传内容UI
 */
@Composable
private fun UploadContent(
    selectedFiles: List<File>,
    isDragging: Boolean,
    onOpenFileSelector: () -> Unit,
    onRemoveFile: (File) -> Unit,
    onPasteFromClipboard: () -> Unit,
    onUpload: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 文件上传区域
        val borderColor = if (isDragging)
            MaterialTheme.colorScheme.primary
        else
            MaterialTheme.colorScheme.outline

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(120.dp)
                .clip(RoundedCornerShape(8.dp))
                .border(
                    width = if (isDragging) 2.dp else 1.dp,
                    color = borderColor,
                    shape = RoundedCornerShape(8.dp)
                )
                .background(
                    if (isDragging)
                        MaterialTheme.colorScheme.primary.copy(alpha = 0.1f)
                    else
                        Color.Transparent
                )
                .clickable { onOpenFileSelector() },
            contentAlignment = Alignment.Center
        ) {
            if (selectedFiles.isEmpty()) {
                // 未选择文件时显示的内容
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    Icon(
                        imageVector = Icons.Outlined.CloudUpload,
                        contentDescription = "上传",
                        modifier = Modifier.size(40.dp),
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = if (isDragging) "释放文件以上传" else "点击选择或拖拽文件到此处",
                        color = MaterialTheme.colorScheme.primary
                    )
                    Text(
                        text = "支持多文件上传",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            } else {
                // 显示已选择文件数量
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    Icon(
                        imageVector = Icons.Outlined.Description,
                        contentDescription = "文件",
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "已选择 ${selectedFiles.size} 个文件",
                        color = MaterialTheme.colorScheme.primary
                    )
                    Text(
                        text = "点击添加更多文件",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }

        // 已选择文件列表
        if (selectedFiles.isNotEmpty()) {
            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = "已选择文件",
                style = MaterialTheme.typography.titleSmall,
                modifier = Modifier
                    .align(Alignment.Start)
                    .padding(vertical = 4.dp)
            )

            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(120.dp)
            ) {
                items(selectedFiles) { file ->
                    FileItemRow(
                        file = file,
                        onRemove = { onRemoveFile(file) }
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 操作按钮区域
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            // 粘贴按钮
            OutlinedButton(
                onClick = { onPasteFromClipboard() },
                modifier = Modifier.weight(1f)
            ) {
                Icon(
                    imageVector = Icons.Outlined.ContentPaste,
                    contentDescription = "粘贴"
                )
                Spacer(modifier = Modifier.width(4.dp))
                Text("粘贴")
            }

            Spacer(modifier = Modifier.width(8.dp))

            // 上传按钮
            Button(
                onClick = { onUpload() },
                enabled = selectedFiles.isNotEmpty(),
                modifier = Modifier.weight(1f)
            ) {
                Text("上传 (${selectedFiles.size})")
            }
        }
    }
}

/**
 * 文件列表项组件
 */
@Composable
private fun FileItemRow(
    file: File,
    onRemove: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            imageVector = Icons.Outlined.Description,
            contentDescription = "文件",
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(16.dp)
        )

        Spacer(modifier = Modifier.width(8.dp))

        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = file.name,
                style = MaterialTheme.typography.bodyMedium,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = formatFileSize(file.length()),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }

        IconButton(
            onClick = onRemove,
            modifier = Modifier.size(24.dp)
        ) {
            Icon(
                imageVector = Icons.Default.Close,
                contentDescription = "移除",
                tint = MaterialTheme.colorScheme.error,
                modifier = Modifier.size(16.dp)
            )
        }
    }
}

/**
 * 上传抽屉组件
 */
@Composable
fun UploadDrawer(direction: DrawerDirection = DrawerDirection.TOP) {
    val viewModel = remember { UseUploadDrawer(direction) }

    // 渲染抽屉
    viewModel.render()
}

/**
 * 使用 AWT FileDialog 选择多个文件
 */
private suspend fun selectMultipleFiles(): List<File>? = withContext(Dispatchers.IO) {
    val fileDialog = FileDialog(Frame(), "选择文件", FileDialog.LOAD)
    fileDialog.isMultipleMode = true // 启用多选
    fileDialog.isVisible = true

    val files = fileDialog.files
    if (files.isNotEmpty()) {
        files.toList()
    } else {
        null
    }
}

/**
 * 格式化文件大小显示
 */
private fun formatFileSize(size: Long): String {
    return when {
        size < 1024 -> "$size B"
        size < 1024 * 1024 -> "${(size / 1024.0).toInt()} KB"
        size < 1024 * 1024 * 1024 -> "${(size / (1024.0 * 1024.0)).toInt()} MB"
        else -> "${(size / (1024.0 * 1024.0 * 1024.0)).toInt()} GB"
    }
}
